import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import router from '@/router'
import _ from 'lodash'
import { useLocalStorageStore } from './local_storage'
import http from '@/api/http.js'

/**
 * 用户相关状态
 */
export const useUserStore = defineStore('user', () => {
    const storage = useLocalStorageStore()

    const _data = ref({
        // 登录验证token
        access_token: '',
        // 备用token
        refresh_token: '',
        // 用户信息
        id: '',
        username: '',
        nickname: '',
        avatar: '',
        mail: '',
        membership: null
    })

    /**
     * 对外开放的响应式数据
     */
    const userinfo = computed(() => _data.value);
    const access_token = computed(() => _data.value.access_token);
    const user_membership = computed(() => _data.value.membership);

    /**
     * 设置数据
     * @param {Object} data  要设置的键值对数据
     * @param {Boolean} isInit  是否初始化行为，若是初始化则不保存本地存储
     */
    function setData(data, isInit = false) {
        _.forOwn(_data.value, (v, k, o) => {
            !_.has(data, k) || (o[k] = data[k])
        })
        isInit || storage.save(_data.value, 'user')
    }

    /**
     * 设置使用点数
     */
    function setUsePoint(num) {
        if(_data.value.membership){
            _data.value.membership.use_number += num
        }
    }


    /**
     * 从本地存储中加载数据
     */
    function loadStorage() {
        setData(storage.get('user', true), true)
    }

    /**
     * 登录成功
     */
    function loginSucceeded(data) {
        setData(data)
        router.push({ path: "/home" })
    }

    /**
     * 是否已登录
     */
    const isLoggedIn = computed(() => !!_data.value.username)

    /**
     * 注销登录
     */
    function logout() {
        storage.remove('user')
        router.replace({ path: "/index" })
    }

    /**
     * 去登录
     */
    function goLogin() {
        router.replace({ path: "/index" })
    }

    /**
     * 获取套餐
     */
    async function userMemberShip() {
        if (isLoggedIn.value){
            const getUserMemberShip = (data, callback) =>http.get('/v1/get_membership' , data, callback, false)
            var res = await getUserMemberShip({})
            setData({'membership': res.data})
        }
            
    }

    return {
        user_membership,
        access_token,
        userinfo,
        setData,
        loadStorage,
        loginSucceeded,
        isLoggedIn,
        logout,
        setUsePoint,
        userMemberShip,
        goLogin,
    }
})
